package com.inyaa.picture.file.controller;

import com.inyaa.base.bean.BaseResult;
import com.inyaa.picture.config.RedisService;
import com.inyaa.picture.file.bean.InyaaSysFile;
import com.inyaa.picture.file.service.InyaaBaseUploadService;
import com.inyaa.picture.file.service.InyaaSysFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
@Slf4j
public class ImageController {

    private final InyaaSysFileService inyaaSysFileService;
    private final Map<String, InyaaBaseUploadService> uploadMap;
    private final RedisService redisService;

    @GetMapping("/list")
    public BaseResult<List<InyaaSysFile>> getMobile() {
        List<InyaaSysFile> list = inyaaSysFileService.findAll();
        return BaseResult.success(list);
    }

    @GetMapping("/image")
    public String getPc(Integer type) {
        InyaaSysFile file = inyaaSysFileService.getRandImg(type);
        return file.getUrl();
    }

    @PostMapping("/delete")
    public BaseResult<String> delete(@RequestBody InyaaSysFile inyaaSysFile) {
        InyaaSysFile bean = inyaaSysFileService.getOne(inyaaSysFile.getId());
        if (bean != null) {
            Map<String, Object> configMap = redisService.hmget("INYAA_CONFIG_1");
            int uploadType = Integer.parseInt(String.valueOf(configMap.get("UPLOAD_TYPE")));
            switch (uploadType) {
                case 1:
                    uploadMap.get("qniUploadService").deleteFile(bean.getUrl(), configMap);
                    break;
                case 2:
                    uploadMap.get("upaiUploadService").deleteFile(bean.getUrl(), configMap);
                    break;
            }
        }
        return BaseResult.success();
    }

    @PostMapping("/upload")
    public BaseResult<String> upload(@RequestParam("file") MultipartFile file, @RequestParam("type") Integer type) {
        Map<String, Object> configMap = redisService.hmget("INYAA_CONFIG_1");
        int uploadType = Integer.parseInt(String.valueOf(configMap.get("UPLOAD_TYPE")));
        String url = null;
        switch (uploadType) {
            case 1:
                url = uploadMap.get("qniUploadService").uploadFile(file, type, configMap);
                break;
            case 2:
                url = uploadMap.get("upaiUploadService").uploadFile(file, type, configMap);
                break;
        }
        return BaseResult.success(url);
    }

}
